#!/bin/bash

# 定义 TF 卡挂载点
MOUNT_POINT="/mnt/mmcblk1"
ID="0001"
FPS="60"

SD_DEVICE="/dev/mmcblk1p1"

TIMESTAMP=$(date +"%Y_%m_%d-%H_%M_%S")

# 新增设备检查
if [ ! -e "$SD_DEVICE" ]; then
    echo "Storage device $SD_DEVICE not found" >&2
    sudo rm -rf "$MOUNT_POINT"
    sync
    exit 1
fi

# 检查挂载点是否存在，如果不存在则创建
if [ ! -d "$MOUNT_POINT" ]; then
    sudo mkdir -p "$MOUNT_POINT"
fi

# 检查分区是否已经挂载
if ! mountpoint -q "$MOUNT_POINT"; then
    # 若未挂载，则挂载 /dev/mmcblk1p1 分区，针对 FAT32 或 exFAT 文件系统
    sudo mount -o rw,uid=1000,gid=1000,umask=0002 "$SD_DEVICE" "$MOUNT_POINT"
else
    # 若已挂载，尝试重新挂载为读写模式
    sudo mount -o remount,rw,uid=1000,gid=1000,umask=0002 "$SD_DEVICE" "$MOUNT_POINT"
fi

# 确保挂载点有写入权限
sudo chmod 777 "$MOUNT_POINT"

DIR_POINT="$MOUNT_POINT"/"$ID"
if [ ! -d "$DIR_POINT" ]; then
    sudo mkdir -p "$DIR_POINT"
fi
sudo chmod 777 "$DIR_POINT"

# 查找 TF 卡中最大编号的 .avi 文件
MAX_NUMBER=0
for file in "$DIR_POINT"/*.avi; do
    if [ -f "$file" ]; then
        filename=$(basename "$file")
        number="${filename%.*}"
        if [[ "$number" =~ ^[0-9]+$ ]]; then
            if [ "$number" -gt "$MAX_NUMBER" ]; then
                MAX_NUMBER="$number"
            fi
        fi
    fi
done

# 新文件编号为最大编号加 1
NEW_NUMBER=$((MAX_NUMBER + 1))
OUTPUT_FILE="$DIR_POINT/${NEW_NUMBER}.avi"
LOG_FILE="$DIR_POINT/${NEW_NUMBER}_log.txt"

if ! df --output=avail "$MOUNT_POINT" | awk 'NR==2 {exit $1 < 1000000}'; then  # 检查剩余空间是否小于1GB
    echo "sd card not enough" >&2
    touch "$DIR_POINT/${NEW_NUMBER}.avi"
    touch "$DIR_POINT/${NEW_NUMBER}_space_error_${TIMESTAMP}.txt"
    sync
    exit 2
fi

sudo /home/radxa/log_recorder.sh "$LOG_FILE" &

# 新增摄像头设备检测
CAMERA_DEVICE=""
for i in {0..5}; do
    if sudo v4l2-ctl -d /dev/video$i --info 2>/dev/null | grep -q "CAMERA"; then
        CAMERA_DEVICE="/dev/video$i"
        break
    fi
done

if [ -z "$CAMERA_DEVICE" ]; then
    echo "No available camera device found" >&2
    touch "$DIR_POINT/${NEW_NUMBER}.avi"
    touch "$DIR_POINT/${NEW_NUMBER}_cap_none_${TIMESTAMP}.txt"
    sync
    exit 3
fi

echo "camera device: $CAMERA_DEVICE"
# 运行 gstreamer 命令进行视频录制
gst-launch-1.0 -v v4l2src device="$CAMERA_DEVICE" ! image/jpeg,width=1920,height=1080,framerate="$FPS"/1 ! jpegparse ! avimux ! filesink location="$OUTPUT_FILE" || (echo "gstreamer fail" && touch "$DIR_POINT/${NEW_NUMBER}_cap_error.txt")

echo "gstreamer sync..."
sync
echo "gstreamer sync success"

TIMESTAMP=$(date +"%Y_%m_%d-%H_%M_%S")
touch "$DIR_POINT/${NEW_NUMBER}_stop_${TIMESTAMP}.txt"  # 修复变量展开语法
if [ ! -f "$DIR_POINT/${NEW_NUMBER}_cap_error.txt" ]; then
    echo "file gstreamer success"
    touch "$DIR_POINT/${NEW_NUMBER}_cap_end.txt"
    echo "gstreamer end"
    sync
    exit 0
fi

sync
echo "gstreamer error"

cd /home/radxa/CV_Web
echo "CV_Web"
sudo python3 ./CV_Web.py
echo "CV_Web_Time"
sudo python3 ./CV_Web_Time.py

exit 4
